package com.cino.fullstack.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cino.fullstack.entity.User;
import com.cino.fullstack.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;

/**
 * 用户管理控制器
 *
 * @author +Le
 * @since 2025-10-20
 */
@Controller
@RequestMapping("/user")
public class UserController {

    private final UserService userService;
    
    // 常量定义
    private static final String PAGE_TITLE = "pageTitle";
    private static final String REDIRECT_USER_LIST = "redirect:/user/list";
    private static final String SUCCESS_MESSAGE = "successMessage";
    private static final String ERROR_MESSAGE = "errorMessage";
    private static final String USER_LIST_VIEW = "user/list";
    private static final String USER_FORM_VIEW = "user/form";
    private static final String USER_INFO_VIEW = "user/info";

    public UserController(UserService userService) {
        this.userService = userService;
    }

    /**
     * 用户列表页面
     */
    @GetMapping("/list")
    public String list(@RequestParam(defaultValue = "1") Integer pageNum,
                       @RequestParam(defaultValue = "10") Integer pageSize,
                       @RequestParam(required = false) String keyword,
                       Model model) {
        // 调用Service层获取用户列表
        Page<User> userPage = userService.getUserList(pageNum, pageSize, keyword);
        
        model.addAttribute("userPage", userPage);
        model.addAttribute("keyword", keyword);
        model.addAttribute(PAGE_TITLE, "用户列表");
        return USER_LIST_VIEW;
    }

    /**
     * 添加用户页面
     */
    @GetMapping("/add")
    public String addForm(Model model) {
        model.addAttribute("user", new User());
        model.addAttribute(PAGE_TITLE, "添加用户");
        return USER_FORM_VIEW;
    }

    /**
     * 编辑用户页面
     */
    @GetMapping("/edit/{id}")
    public String editForm(@PathVariable Long id, Model model) {
        // 调用Service层获取用户信息
        User user = userService.getUserById(id);
        if (user == null) {
            return REDIRECT_USER_LIST;
        }
        model.addAttribute("user", user);
        model.addAttribute(PAGE_TITLE, "编辑用户");
        return USER_FORM_VIEW;
    }

    /**
     * 查看用户详情
     */
    @GetMapping("/info/{id}")
    public String getInfo(@PathVariable Long id, Model model) {
        // 调用Service层获取用户信息
        User user = userService.getUserById(id);
        if (user == null) {
            return REDIRECT_USER_LIST;
        }
        model.addAttribute("user", user);
        model.addAttribute(PAGE_TITLE, "用户详情");
        return USER_INFO_VIEW;
    }

    /**
     * 保存用户（创建或更新）
     */
    @PostMapping("/save")
    public String save(@ModelAttribute User user, RedirectAttributes redirectAttributes) {
        try {
            if (user.getId() == null) {
                // 新增用户 - 调用Service层业务逻辑
                boolean success = userService.saveUser(user);
                if (success) {
                    redirectAttributes.addFlashAttribute(SUCCESS_MESSAGE, "用户添加成功！");
                } else {
                    redirectAttributes.addFlashAttribute(ERROR_MESSAGE, "用户添加失败！");
                }
            } else {
                // 更新用户 - 调用Service层业务逻辑
                boolean success = userService.updateUser(user);
                if (success) {
                    redirectAttributes.addFlashAttribute(SUCCESS_MESSAGE, "用户更新成功！");
                } else {
                    redirectAttributes.addFlashAttribute(ERROR_MESSAGE, "用户更新失败！");
                }
            }
        } catch (IllegalArgumentException e) {
            // 业务异常，显示具体错误信息
            redirectAttributes.addFlashAttribute(ERROR_MESSAGE, e.getMessage());
        } catch (Exception e) {
            // 系统异常
            redirectAttributes.addFlashAttribute(ERROR_MESSAGE, "操作失败：" + e.getMessage());
        }
        return REDIRECT_USER_LIST;
    }

    /**
     * 删除用户
     */
    @GetMapping("/delete/{id}")
    public String delete(@PathVariable Long id, RedirectAttributes redirectAttributes) {
        try {
            // 调用Service层业务逻辑
            boolean success = userService.deleteUser(id);
            if (success) {
                redirectAttributes.addFlashAttribute(SUCCESS_MESSAGE, "用户删除成功！");
            } else {
                redirectAttributes.addFlashAttribute(ERROR_MESSAGE, "用户删除失败！");
            }
        } catch (IllegalArgumentException e) {
            // 业务异常，显示具体错误信息
            redirectAttributes.addFlashAttribute(ERROR_MESSAGE, e.getMessage());
        } catch (Exception e) {
            // 系统异常
            redirectAttributes.addFlashAttribute(ERROR_MESSAGE, "删除失败：" + e.getMessage());
        }
        return REDIRECT_USER_LIST;
    }

    /**
     * 批量删除用户
     */
    @PostMapping("/batchDelete")
    public String batchDelete(@RequestParam("ids") List<Long> ids, RedirectAttributes redirectAttributes) {
        try {
            // 调用Service层业务逻辑
            boolean success = userService.batchDeleteUsers(ids);
            if (success) {
                redirectAttributes.addFlashAttribute(SUCCESS_MESSAGE, "批量删除成功！");
            } else {
                redirectAttributes.addFlashAttribute(ERROR_MESSAGE, "批量删除失败！");
            }
        } catch (IllegalArgumentException e) {
            // 业务异常，显示具体错误信息
            redirectAttributes.addFlashAttribute(ERROR_MESSAGE, e.getMessage());
        } catch (Exception e) {
            // 系统异常
            redirectAttributes.addFlashAttribute(ERROR_MESSAGE, "批量删除失败：" + e.getMessage());
        }
        return REDIRECT_USER_LIST;
    }
}
